<?php

namespace app\common\service;

/**
 * 管理员Token
 * Class AdminToken
 * @package app\common\service
 */
class AdminToken
{

    public function __construct()
    {
        $this->redis = initRedis();
    }


    public function getValue(string $token): array
    {
        $key = config('token.admin_prefix') . 'admin:' . $token;
        $rs  = $this->redis->get($key);
        if ($rs) {
            $val = json_decode($rs, true);
        } else {
            $val = [];
        }
        return $val;
    }

    /**
     * 设置token
     * @param int $uid
     * @param array $value 需要存储的值
     * @return array
     */
    public function setToken(int $uid, array $value = []): array
    {
        $token = 'admin' . md5($uid . '@' . time() . '#' . rand(1000, 9999));
        //redis设置token
        $expire             = intval(time() + config('token.admin_expire'));
        $key                = config('token.admin_prefix') . 'admin:' . $token;
        $value['uid']       = $uid;
        $value['logintime'] = date('Y-m-d H:i:s');
        $value['expire']    = date('Y-m-d H:i:s', $expire);
        $this->redis->setex($key, config('token.admin_expire'), json_encode($value));
        $value['admin_token'] = $token;
        return $value;
    }

    /**
     * 刷新过期时间
     */
    public function refreshExpire(string $token)
    {
        $expire = intval(time() + config('token.admin_expire'));
        $key    = config('token.admin_prefix') . 'admin:' . $token;
        $value  = $this->redis->get($key);
        if ($value) {
            $data            = json_decode($value,true);
            $data['expire']    = date('Y-m-d H:i:s', $expire);
            //echo  json_encode($value);
            $this->redis->setex($key, config('token.admin_expire'), json_encode($data));
        }
    }

    /**
     * 删除token
     * @param string $token
     */
    public function deleteToken(string $token): bool
    {
        $key = config('token.admin_prefix') . 'admin:' . $token;

        $this->redis->del($key);
        return true;

    }
}